package com.xw.controller;

import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.xw.common.Constants;
import com.xw.common.Result;
import com.xw.common.TokenHandler;
import com.xw.dao.PostCodeDao;
import com.xw.entity.PostCode;
import com.xw.entity.User;
import com.xw.req.PageRequest;
import com.xw.service.PostCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jsoup.Jsoup;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author 72478
 * @Description: 帖子发布表
 * @Date: 2024/12/18 16:53
 * @Version: 1.0
 */
@RestController
@RequestMapping("postCode")
@Api(tags = "帖子发布表")
public class PostCodeController {
    /**
     * 服务对象
     */
    @Resource
    private PostCodeService postCodeService;

    @Resource
    private PostCodeDao postCodeDao;

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @PostMapping("/page")
    @ApiOperation(value = "分页查询")
    public Result<?> findPage(@RequestBody PageRequest<PostCode> pageRequest) {
        return new Result<>(this.postCodeService.queryByPage(pageRequest),Constants.SUCCESS);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "查询单条数据（ID）")
    public Result<?> findOne(@PathVariable("id") Integer id) {
        PostCode postCode =  this.postCodeDao.queryById(id);
        return new Result<>(postCode,Constants.SUCCESS);
    }

    /**
     * 发送帖子
     * @param postCode 实体
     */
    @PostMapping
    @ApiOperation(value = "发送帖子")
    public Result<?> saveOrUpdate(@RequestBody @Validated PostCode postCode) {
        User userInfo = TokenHandler.getUserInfo();
        postCode.setSendUserId(userInfo.getId());
        postCode.setSendTime(new Date());
        postCode.setSendUserName(userInfo.getNickName());

        String content = Jsoup.parse(postCode.getContent()).text();
        // 使用SensitiveWordHelper检查帖子内容是否包含敏感词
        if (SensitiveWordHelper.contains(content)){
            // 如果包含敏感词，返回错误信息
            return new Result<>(Constants.ERROR, "帖子内容包含敏感词，无法发布");
        }

        // 如果不包含敏感词，继续保存或更新帖子
        if (postCode.getId() == null) {
            this.postCodeDao.insert(postCode);
        } else {
            this.postCodeDao.update(postCode);
        }
        return new Result<>(Constants.SUCCESS);
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除数据(ID)")
    public Result<?> delete(@PathVariable("id") Integer id) {
        postCodeService.delete(id);
        return new Result<>(Constants.SUCCESS);
    }

    @GetMapping("postType")
    @ApiOperation(value = "获取帖子类型")
    public Result<?> postType() {
        List<PostCode> postCodes = this.postCodeDao.queryAll();
        List<String> typeList = postCodes.stream().map(PostCode::getType).distinct().collect(Collectors.toList());
        return new Result<>(typeList,Constants.SUCCESS);
    }

    @PostMapping("updatePostcode")
    @ApiOperation(value = "修改邮编信息")
    public Result<?> updatePostcode(@RequestBody @Validated PostCode postCode) {
        postCodeDao.update(postCode);
        return new Result<>(Constants.SUCCESS);
    }

    @GetMapping("/getMyPosts")
    @ApiOperation(value = "获取当前用户发布的所有帖子")
    public Result<?> getMyPosts() {
        try {
            User userInfo = TokenHandler.getUserInfo();
            Integer userId = userInfo.getId();
            List<PostCode> posts = postCodeDao.queryByUserId(userId);
            return new Result<>(posts, Constants.SUCCESS);
        } catch (Exception e) {
            return new Result<>(Constants.ERROR, "服务器错误");
        }
    }

}